package com.laifeng.sopcastsdk.local;

import android.util.Log;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by jiaqing on 2018/1/9.
 */

public class LocalVideoFileManager {

    private List<String> mVideoNameList = new ArrayList<String>();

    private static LocalVideoFileManager mInstance;

    public synchronized static LocalVideoFileManager getInstance() {
        if (mInstance == null) {
            mInstance = new LocalVideoFileManager();
        }

        return mInstance;
    }

    private LocalVideoFileManager() {
        listFileAndOrderByDate();
    }

    private void listFileAndOrderByDate() {
        File videoDir = FileUtil.getVideoDir();
        File[] files = videoDir.listFiles();
        for (File file : files) {
            String fileName = file.getName();
            mVideoNameList.add(fileName);
        }

        Collections.sort(mVideoNameList, new Comparator<String>() {
            @Override
            public int compare(String lhs, String rhs) {
                return lhs.compareTo(rhs);
            }
        });
    }

    private void clearVideoFileIfNecessary(long size) {

        Log.e("YJQ", "leftStorage>>>" + FileUtil.getAvailableSize());

        if (FileUtil.getAvailableSize() <= 104857600L) {
            long clearSpace = 0;
            Iterator<String> iterator = mVideoNameList.iterator();
            while (iterator.hasNext()) {
                String fileName = iterator.next();

                Log.e("YJQ", "fileName>>>" + fileName);

                File videoFile = new File(FileUtil.getVideoDir(), fileName);
                if (!videoFile.exists()) {
                    //file not exist
                    iterator.remove();
                    continue;
                }

                if (!videoFile.delete()) {
                    //delete another file if failed
                    continue;
                }

                //delete file success
                iterator.remove();
                clearSpace += videoFile.length();

                if (clearSpace >= size) {
                    //clear enough space
                    break;
                }
            }
        }
    }

    public File getEmptyFile(long size) {
        clearVideoFileIfNecessary(size);
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = formater.format(new Date()) + ".flv";

        //add file name into list
        mVideoNameList.add(fileName);

        return new File(FileUtil.getVideoDir(), fileName);
    }
}
